<template>
  <el-dialog v-model="visible" title="录入公式" width="600px" @closed="close">
    <div class="calculator-display">
      <el-input v-model="expression" readonly />
    </div>
    <div class="calculator-buttons">
      <el-button v-for="btn in buttons" :key="btn" class="calc-btn" @click="appendToExpression(btn)">
        {{ btn }}
      </el-button>
    </div>
    <div class="calculator-actions">
      <el-button type="warning" @click="clearExpression">清空</el-button>
      <el-button type="primary" @click="confirmExpression">确认</el-button>
    </div>
  </el-dialog>
</template>

<script setup>
import { ref, defineExpose } from "vue";

const visible = ref(false);
const expression = ref("");
const callback = ref(null);
const inputRef = ref(null); // 记录输入框的 ref

// 计算器按钮列表
const buttons = ref([
  "0", "1",  "2", "3","4", "5","6", "7","8", "9",
  "+","-", "*", "/",  ".","(", ")","%",
  "长", "生产长","宽", "生产宽",  "高", "生产高", 
  "单价",  "基重",  "厚度", 
  "加分",  "钉条", "产品重量", 
  "片接数", "模长", "模宽", "模数", "长插数", "宽插数",
  "毛板长", "毛板宽", "参数1", "参数2", "参数3", "参数4",
  "参数5", "参数6", "参数7", "参数8", "参数9", "参数10",
  "参数11", "参数12", "参数13", "参数14", "参数15", "参数16",
  "参数17", "参数18", "参数19", "参数20", "订单数", "生产数",
  "体积系数", "开槽宽", "长开", "宽开", "计算宽", "计算长",
  "净板系数", "毛板系数", "参数类型01", "参数类型02", "参数类型03",
  "参数类型04", "参数类型05", "参数类型06", "参数类型07",
  "参数类型08", "参数类型09", "参数类型10"
]);

// 显示计算器
const open = (cb, refInput) => {
  visible.value = true;
  expression.value = "";
  callback.value = cb;
  inputRef.value = refInput;
};

// 追加输入
const appendToExpression = (val) => {
  expression.value += val;
};

// 清空输入
const clearExpression = () => {
  expression.value = "";
};

// 确认输入
const confirmExpression = () => {
  if (callback.value) callback.value(expression.value);
  visible.value = false;

  // 让输入框失去焦点
  if (inputRef.value) {
    inputRef.value.blur();
  }
};

// 关闭时清空
const close = () => {
  expression.value = "";
};

// 让父组件可以调用 open 方法
defineExpose({ open });
</script>
<style scoped>
.calculator-display {
  margin-bottom: 10px;
}

.calculator-buttons {
  display: grid;
  grid-template-columns: repeat(5, 1fr); /* 5列布局 */
  gap: 5px;
  max-height: 600px; /* 让按钮区更大 */
  overflow-y: auto; /* 超出部分滚动 */
  padding: 10px;
}

/* 修正按钮对齐 */
.calc-btn {
  width: 100%;
  min-height: 50px; /* 按钮更大 */
  font-size: 14px; /* 字体调整 */
  font-weight: bold;
  text-align: center;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0; /* 避免默认 margin 影响 */
  padding: 0; /* 避免按钮内部额外填充 */
  box-sizing: border-box; /* 确保边框不会影响尺寸 */
}

.calculator-actions {
  display: flex;
  justify-content: space-between;
  margin-top: 10px;
}
</style>
